import { observer, useLocalStore } from 'mobx-react';
import React, { useCallback, useEffect, useRef } from 'react';

import initScrollView from '@/cross/components/ScrollView';
import initText from '@/cross/components/Text';
import initView from '@/cross/components/View';
const View = initView({});
const Text = initText({});
const ScrollView = initScrollView({});

import { Client } from '@/config';
import { AutoForm, HeaderBar, Modal, Page, Tag } from '@/cross/components';
import { $throttle, px } from '@/cross/utils';
import { GoodsMessageItem } from '@/types';
import { AutoFormParams } from '../../../../utils/form';

@observer
class FormFieldItemAttrConfigModal extends React.Component<FormFieldItemAttrConfigProps> {
  render() {
    return (
      <Page {...this.props}>
        <HeaderBar title="更多设置" titleAlign="left" mode="light" leftContent={null} showBack />
        <ScrollView>
          <View className="M-height-40" />
        </ScrollView>
      </Page>
    );
  }
}

// @observer
// class FormFieldItemOptionsEditor extends React.Component<FormFieldItemAttrConfigProps> {

//   render() {
//     return (
//       <View>
//         <AutoForm<ISuperFormDataFieldOption>
//           theme='light'
//           config={{
//             fields: [
//             ]
//           }}
//         />
//       </View>
//     );
//   }

// }

/**
 * 题目属性设置
 */

interface FormFieldItemAttrConfigProps {
  value: object;
  values: object;
  onChange: (field: string, value?: any) => void;
}

export const FormFieldItemAttrConfig = ({
  value,
  values,
  onChange,
}: FormFieldItemAttrConfigProps) => {
  const putModalRef = useRef<Modal<FormFieldItemAttrConfigModal>>(null);

  const open = useCallback(() => {
    putModalRef.current?.open({
      value,
      values,
      onChange,
    });
  }, []);

  return (
    <View>
      <Tag size="small" color="geekblue" active circle onClick={open}>
        更多设置
      </Tag>
      <Modal<FormFieldItemAttrConfigModal>
        ref={putModalRef}
        zIndex={10}
        width={Client === 'worktop' ? px(2000) : px(750)}
        height={Client === 'worktop' ? 'calc(40vh)' : undefined}
        renderView={(props) => <FormFieldItemAttrConfigModal {...props} />}
      />
    </View>
  );
};

interface IProps {
  name?: string | number;
  value?: GoodsMessageItem[];
  onChange?: (
    name: string | number | GoodsMessageItem[] | '',
    value?: GoodsMessageItem[] | '',
  ) => void;
}

export const FormSchemaEditor = observer(({ name, value, onChange }: IProps) => {
  interface IFormValues {
    messages: GoodsMessageItem[];
  }

  interface IForm {
    values: IFormValues;
    onChange: (values: IFormValues) => void;
  }

  const SuperFormFieldForm: AutoFormParams<any> = {
    defaultValue: {
      name: '',
      type: 'text',
      required: false,
    },
    fields: [
      {
        widget: 'item-rows',
        labelProps: { className: 'M-m-t-10' },
        field: 'value',
        widgetProps: {
          gutter: [10, 10],
        },
        childs: [
          {
            viewProps: { span: 24 },
            params: {
              type: 'string',
              field: 'name',
              widget: 'text',
              widgetProps: { placeholder: '标题', type: 'text' },
            },
          },
          {
            viewProps: { span: 9 },
            params: {
              type: 'string',
              field: 'type',
              widget: 'select',
              value: 'text',
              f_options: [
                { value: 'text', label: '文本格式' },
                { value: 'number', label: '数字格式' },
                { value: 'select', label: '单项选择' },
                { value: 'mulitple-select', label: '多项选择' },
                { value: 'form', label: '子表单' },
                { value: 'date', label: '日期' },
                { value: 'time', label: '时间' },
                { value: 'datetime', label: '日期-时间' },
                { value: 'idcard', label: '身份证号' },
                { value: 'phone', label: '手机号' },
                { value: 'image', label: '图片' },
                { value: 'email', label: '邮箱' },
              ],
            },
          },
          {
            viewProps: { span: 4 },
            params: {
              widget: 'custom',
            },
          },
          {
            viewProps: { span: 5 },
            params: {
              type: 'boolean',
              field: 'required',
              widget: 'switch',
              widgetProps: {
                type: 'checkbox',
              },
              labelProps: {
                left: (
                  <View className="M-p-r-5 M-vertical-middle">
                    <Text className="M-f-s-12 M-f-c-666">必填</Text>
                  </View>
                ),
              },
            },
          },
          {
            viewProps: { span: 6 },
            params: {
              field: 'property',
              widget: 'custom',
              render: (field, value, values, onChange) => {
                return (
                  <FormFieldItemAttrConfig value={value} values={values} onChange={onChange} />
                );
              },
            },
          },
        ],
      },
      {
        display: (values) => values.type === 'select',
        label: '选择项',
        field: 'options',
        widget: 'auto-array-form',
        widgetProps: {
          addButtonText: '添加选项',
        },
        form: {
          defaultValue: {
            label: '',
          },
          fields: [
            {
              labelProps: { className: 'M-p-t-10' },
              type: 'string',
              field: 'label',
              widget: 'text',
              widgetProps: { placeholder: '选项', type: 'text' },
            },
          ],
        },
      },
      {
        display: (values) => values.type === 'form',
        label: '子表单',
        field: 'form',
        widget: 'auto-form',
        formStyle: {
          paddingTop: px(20),
        },
        form: {
          defaultValue: {
            messages: [],
          },
          fields: [
            {
              widget: 'auto-array-form',
              field: 'messages',
              widgetProps: { theme: 'light', addButtonText: '添加题目' },
              form: {
                defaultValue: {
                  name: '',
                  type: 'text',
                  required: false,
                },
                fields: [
                  {
                    widget: 'item-rows',
                    labelProps: { className: 'M-m-t-10' },
                    field: 'value',
                    widgetProps: {
                      gutter: [10, 10],
                    },
                    childs: [
                      {
                        viewProps: { span: 24 },
                        params: {
                          type: 'string',
                          field: 'name',
                          widget: 'text',
                          widgetProps: { placeholder: '标题', type: 'text' },
                        },
                      },
                      {
                        viewProps: { span: 9 },
                        params: {
                          type: 'string',
                          field: 'type',
                          widget: 'select',
                          value: 'text',
                          f_options: [
                            { value: 'text', label: '文本格式' },
                            { value: 'number', label: '数字格式' },
                            { value: 'select', label: '单项选择' },
                            { value: 'mulitple-select', label: '多项选择' },
                            { value: 'form', label: '子表单' },
                            { value: 'date', label: '日期' },
                            { value: 'time', label: '时间' },
                            { value: 'datetime', label: '日期-时间' },
                            { value: 'idcard', label: '身份证号' },
                            { value: 'phone', label: '手机号' },
                            { value: 'image', label: '图片' },
                            { value: 'email', label: '邮箱' },
                          ],
                        },
                      },
                      {
                        viewProps: { span: 4 },
                        params: {
                          widget: 'custom',
                        },
                      },
                      {
                        viewProps: { span: 5 },
                        params: {
                          type: 'boolean',
                          field: 'required',
                          widget: 'switch',
                          widgetProps: {
                            type: 'checkbox',
                          },
                          labelProps: {
                            left: (
                              <View className="M-p-r-5 M-vertical-middle">
                                <Text className="M-f-s-12 M-f-c-666">必填</Text>
                              </View>
                            ),
                          },
                        },
                      },
                      {
                        viewProps: { span: 6 },
                        params: {
                          field: 'property',
                          widget: 'custom',
                          render: (field, value, values, onChange) => {
                            return (
                              <FormFieldItemAttrConfig
                                value={value}
                                values={values}
                                onChange={onChange}
                              />
                            );
                          },
                        },
                      },
                    ],
                  },
                  {
                    display: (values) => values.type === 'select',
                    label: '选择项',
                    field: 'options',
                    widget: 'auto-array-form',
                    widgetProps: {
                      addButtonText: '添加选项',
                    },
                    form: {
                      defaultValue: {
                        label: '',
                      },
                      fields: [
                        {
                          labelProps: { className: 'M-p-t-10' },
                          type: 'string',
                          field: 'label',
                          widget: 'text',
                          widgetProps: { placeholder: '选项', type: 'text' },
                        },
                      ],
                    },
                  },
                ],
              },
            },
          ],
        },
      },
    ],
  };

  const form = useLocalStore<IForm>(() => ({
    values: {
      messages: [],
    },
    onChange: $throttle(
      (values: IFormValues) => {
        const { messages } = values;
        console.log('[messages] ', messages);
        if (typeof name === 'undefined') {
          onChange?.(messages);
        } else {
          onChange?.(name, messages);
        }
        form.values = values;
      },
      200,
      {
        leading: true,
        trailing: false,
      },
    ),
  }));

  useEffect(() => {
    // 下面一行解决初始化时和快速赋值 导致防抖让真正的值无法传入
    if (!(value && value.length === form.values.messages.length)) {
      form.onChange({
        messages: value || [],
      });
    }
  }, [value]);

  return (
    <AutoForm<IFormValues>
      theme="light"
      config={{
        fields: [
          {
            widget: 'auto-array-form',
            field: 'messages',
            widgetProps: { theme: 'light', addButtonText: '添加题目' },
            form: SuperFormFieldForm,
          },
        ],
      }}
      value={form.values}
      onChange={form.onChange as any}
    />
  );
});

export default FormSchemaEditor;
